/**
 * 用户配置状态管理 Store
 * 支持本地存储和云端同步
 */

import { defineStore } from 'pinia';
import { ref, watch } from 'vue';
import { ConfigService, type UserConfig } from '@/services/config.service';
import { useAuthStore } from './auth';

const DEFAULT_CONFIG: UserConfig = {
  case_sensitive: false,
  sound_enabled: true,
  duration: 60,
  sequence_length: 200,
};

/**
 * 用户配置管理 Store
 */
export const useConfigStore = defineStore('config', () => {
  // State
  const caseSensitive = ref<boolean>(DEFAULT_CONFIG.case_sensitive);
  const soundEnabled = ref<boolean>(DEFAULT_CONFIG.sound_enabled);
  const duration = ref<number>(DEFAULT_CONFIG.duration);
  const sequenceLength = ref<number>(DEFAULT_CONFIG.sequence_length);
  const isLoading = ref<boolean>(false);
  const error = ref<string | null>(null);
  const useCloudSync = ref<boolean>(false); // 是否启用云端同步

  const authStore = useAuthStore();

  // Actions
  /**
   * 从后端加载配置
   */
  async function loadFromCloud() {
    if (!authStore.isAuthenticated) {
      useCloudSync.value = false;
      return;
    }

    try {
      isLoading.value = true;
      error.value = null;
      
      const config = await ConfigService.getConfig();
      
      caseSensitive.value = config.case_sensitive;
      soundEnabled.value = config.sound_enabled;
      duration.value = config.duration;
      sequenceLength.value = config.sequence_length;
      
      // 同步到本地存储
      saveToLocal();
      
      useCloudSync.value = true;
    } catch (e: any) {
      error.value = e.message || '从云端加载配置失败';
      useCloudSync.value = false;
    } finally {
      isLoading.value = false;
    }
  }

  /**
   * 保存配置到后端
   */
  async function saveToCloud() {
    if (!authStore.isAuthenticated) {
      useCloudSync.value = false;
      return;
    }

    try {
      isLoading.value = true;
      error.value = null;
      
      const config: Partial<UserConfig> = {
        case_sensitive: caseSensitive.value,
        sound_enabled: soundEnabled.value,
        duration: duration.value,
        sequence_length: sequenceLength.value,
      };
      
      await ConfigService.updateConfig(config);
      
      useCloudSync.value = true;
    } catch (e: any) {
      error.value = e.message || '保存到云端失败';
      useCloudSync.value = false;
      // 保存到本地作为备选
      saveToLocal();
    } finally {
      isLoading.value = false;
    }
  }

  /**
   * 保存配置到本地存储
   */
  function saveToLocal() {
    const config: UserConfig = {
      case_sensitive: caseSensitive.value,
      sound_enabled: soundEnabled.value,
      duration: duration.value,
      sequence_length: sequenceLength.value,
    };
    localStorage.setItem('typingGameConfig', JSON.stringify(config));
  }

  /**
   * 从本地存储加载配置
   */
  function loadFromLocal() {
    const saved = localStorage.getItem('typingGameConfig');
    if (saved) {
      try {
        const config: UserConfig = JSON.parse(saved);
        caseSensitive.value = config.case_sensitive ?? DEFAULT_CONFIG.case_sensitive;
        soundEnabled.value = config.sound_enabled ?? DEFAULT_CONFIG.sound_enabled;
        duration.value = config.duration ?? DEFAULT_CONFIG.duration;
        sequenceLength.value = config.sequence_length ?? DEFAULT_CONFIG.sequence_length;
      } catch (e) {
        console.error('Failed to load config from local:', e);
      }
    }
  }

  /**
   * 更新大小写配置
   */
  async function updateCaseSensitive(enabled: boolean) {
    caseSensitive.value = enabled;
    if (useCloudSync.value) {
      await saveToCloud();
    } else {
      saveToLocal();
    }
  }

  /**
   * 更新音效配置
   */
  async function updateSoundEnabled(enabled: boolean) {
    soundEnabled.value = enabled;
    if (useCloudSync.value) {
      await saveToCloud();
    } else {
      saveToLocal();
    }
  }

  /**
   * 更新默认时长配置
   */
  async function updateDuration(durationMinutes: number) {
    duration.value = durationMinutes;
    if (useCloudSync.value) {
      await saveToCloud();
    } else {
      saveToLocal();
    }
  }

  /**
   * 更新序列长度配置
   */
  async function updateSequenceLength(length: number) {
    sequenceLength.value = length;
    if (useCloudSync.value) {
      await saveToCloud();
    } else {
      saveToLocal();
    }
  }

  /**
   * 清除错误
   */
  function clearError() {
    error.value = null;
  }

  /**
   * 初始化配置
   */
  async function init() {
    // 如果已认证，先尝试从云端加载
    if (authStore.isAuthenticated) {
      await loadFromCloud();
    }
    
    // 如果云端加载失败或未认证，加载本地配置
    if (!useCloudSync.value) {
      loadFromLocal();
    }
  }

  // 监听认证状态变化
  watch(
    () => authStore.isAuthenticated,
    async (isAuth) => {
      if (isAuth) {
        await loadFromCloud();
      } else {
        useCloudSync.value = false;
        loadFromLocal();
      }
    },
    { immediate: true }
  );

  return {
    // State
    caseSensitive,
    soundEnabled,
    duration,
    sequenceLength,
    isLoading,
    error,
    useCloudSync,
    // Actions
    updateCaseSensitive,
    updateSoundEnabled,
    updateDuration,
    updateSequenceLength,
    loadFromCloud,
    saveToCloud,
    loadFromLocal,
    saveToLocal,
    clearError,
    init,
  };
});
